package com.wss.lsl.lucene.demo.shipin.filter;

import java.io.IOException;
import java.util.Stack;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.util.AttributeSource;

import com.wss.lsl.lucene.demo.shipin.sameword.engine.SamewordContext;

public class MySameTokenizerFilter extends TokenFilter {

	private CharTermAttribute cta = null;
	private PositionIncrementAttribute pia = null;
	private AttributeSource.State current = null;
	private Stack<String> sames = null;
	private SamewordContext samewordContext;


	public MySameTokenizerFilter(TokenStream input,
			SamewordContext samewordContext) {
		super(input);
		cta = this.addAttribute(CharTermAttribute.class);
		pia = this.addAttribute(PositionIncrementAttribute.class);
		sames = new Stack<String>();
		this.samewordContext = samewordContext;

	}

	@Override
	public boolean incrementToken() throws IOException {
		System.out.println(cta);
		System.out.println(pia.getPositionIncrement());
		while (sames.size() > 0) {
			restoreState(current);
			// System.out.println("---"+cta);
			cta.setEmpty();
			cta.append(sames.pop());
			pia.setPositionIncrement(0);
			return true;
		}

		if (!input.incrementToken()) {
			return false;
		}
		if (getSameWords(cta.toString())) {
			current = captureState();
		}

		return true;
	}

	private boolean getSameWords(String name) {
		String[] sws = samewordContext.getSamewords(name);
		if (sws != null) {
			for (String s : sws) {
				sames.push(s);
			}
			return true;
		}
		return false;
	}
}
